package com.cnsuning.jobtool.jobtools.reline;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Repaire {

    @Test
    public void repaire() throws IOException {
        File file = new File("src\\main\\java\\com\\cnsuning\\jobtool\\jobtools\\reline\\files\\DEP2019123100155.164742.629-1.csv");
        List<String> oldLines = FileUtils.readLines(file);
        List<Integer> errorLineIndex = new ArrayList<>();
        for (int i = 0; i < oldLines.size(); i++) {
            String line = oldLines.get(i);
            try {
                if (line.indexOf("\",") > 0) {
                    int rowid = Integer.parseInt(line.substring(1, line.indexOf("\",")));
                }
            } catch (NumberFormatException e) {
//                e.printStackTrace();
                errorLineIndex.add(i);
                continue;
            }
            if (!line.startsWith("\"") || (line.indexOf("\",") == 0)){
                errorLineIndex.add(i);
            }
        }

        for (Integer index: errorLineIndex){
            if (index == 0) continue;
            String s = oldLines.get(index - 1);
            if (s.endsWith("\n")){
                s = s.substring(0,s.lastIndexOf("\n"));
                oldLines.set(index-1,s);
            }
        }
        if (file.exists())
        {
            file.delete();
        }
        for (String lineStr:oldLines)
        {
            FileUtils.writeStringToFile(file,lineStr,"utf-8",true);
        }


    }

    @Test
    public void test() throws IOException {
        File file = new File("C:\\Users\\徐兴兴\\Desktop\\1.txt");
        FileUtils.writeStringToFile(file,"\n");
    }

}
